<?php
declare (strict_types = 1);

namespace app\model;

use think\Model;

/**
 * @mixin \think\Model
 */
class Category extends Model
{
    /**
     * 获取所有子分类
     * @return array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getCategories(){

        $all = self::field('id,cate_name,cid,pid')->select();

        $data = $all->toArray();

        $all = getChild($data,0,'pid');

        $all = array_values($all);

        foreach($all as $k=>$v){
            $all[$k]['child'] = array_values($v['child']);
        }

        return $all;
    }

    /**
     * 获取分类下所有子分类的物料id
     * @param int $cid
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getCategoryIds($cid=0){

        $all = self::getCategories();

        $ids = [];
        $idsStr = '';
        if($all){
            foreach($all as $k=>$v){
                if($cid == $v['cid']){
                    $ids[] = $v['cid'];

                    if($v['child']){
                        foreach($v['child'] as $k2=>$v2){
                            $ids[] = $v2['cid'];
                        }
                    }

                    break;
                }
            }

            if($ids){

                if(is_array($ids)){
                    $idsStr = implode(',',$ids);
                }else{
                    foreach($ids as $k3=>$v3){
                        $idsStr .= $v3['cid'].',';
                    }

                    $idsStr != '' ? rtrim($idsStr,',') : $idsStr;
                }

            }
        }

        return $idsStr;
    }
}
